package main

import (
	"strings"
	"strconv"
	"github.com/codeskyblue/go-sh"
	//"fmt"
	"time"
)

func DoCronJob(StrNowTime string){
	project_ids := GetHandleProjectId()

	for _, project_id := range project_ids {
		jobs := GetCronJobs(project_id)
		for _, job := range jobs {
			go runCronJob(StrNowTime,job)
		}
	}
}

func GetJobsTimeout() (map[string]int64) {
	JobsTimeout := make(map[string]int64)
	project_ids := GetHandleProjectId()

	var timeout int64

	for _, project_id := range project_ids {
		jobs := GetCronJobs(project_id)
		for _, job := range jobs {
			timeout,_ = strconv.ParseInt(job["timeout"],10,64)
			JobsTimeout[job["id"]] = timeout
		}
	}
	return JobsTimeout
}

func DoAlarm(){
	NowTime := time.Now().Unix()
	JobsTimeout := GetJobsTimeout()
	AlarmTaskLogs := GetAlarmTaskLog()

	for _,log := range AlarmTaskLogs{
		StartTime := StrTimeToUnix(log["exec_start_time"])

		if NowTime-StartTime > JobsTimeout[log["task_id"]]{
			taskAlarms := getTaskAlarmsByTaskId(log["task_id"])
			if 0 == len(taskAlarms){
				continue
			}

			job := getJobByTaskId(log["task_id"])
			message := job["add_time"]+"执行的定时任务"+job["id"]+" "+job["task_name"]
			if log["status"] == string(2){
				message += "执行失败"
			}else if log["status"] == string(0){
				message += "执行超时"
			}

			for _,taskAlarm := range taskAlarms{
				sendMessage(taskAlarm["phone_code"],message)
			}
			AlarmEnd(log["id"])
		}
	}
}


//获取需要处理项目ID
func GetHandleProjectId() (map[int]string){
	projects := GetAllProjects()
	i := 0
	ret := make(map[int]string)
	for _, project := range projects {
		ret[i] = project["id"]
	}
	return ret
}

//执行定时脚本
func runCronJob(StrNowTime string,job map[string]string) bool{

	//检查当前时间是否需要执行定时程序
	if checkTime(job["execution_frequency"],StrNowTime) == false {
		return false;
	}

	var JobTimeOut int64 = 0
	//加锁
	JobTimeOut,_ = strconv.ParseInt(job["timeout"], 10, 64)
	Lock := JobLock(job["id"],JobTimeOut,"Job")

	if Lock ==  0{
		return false;
	}


	//执行脚本
	runJob(job)

	JobUnLock(job["id"],Lock,"Job")
	return true
}

func GetCommands() (map[string]string){
	commends := GetAllCommands()
	ret := make(map[string]string)
	for _, commend := range commends {
		ret[commend["id"]] = commend["command"]
	}
	return ret
}

//执行脚本方法
func runJob(job map[string]string){

	commends := GetCommands()

	//记录开始运行
	run_id := JobStart(job)
	run_id_str := strconv.FormatInt(run_id, 10)
	//运行
	session := sh.NewSession()
	session.SetDir("/")
	session.SetEnv("x_run_id", run_id_str)
	param := strings.Split(job["params"], " ")
	output, err := session.Command(commends[job["command_id"]], param).Output()

	var succ bool
	var exec_export string
	if err != nil {
		succ = false
		ErrorLog(err)
		exec_export = string(output)+"\n"+err.Error()
	}else{
		succ = true
		exec_export = string(output)
	}
	//记录运行结果
	JobEnd(run_id, succ, exec_export)
}

//依据crontab的时间检查是否需要执行
func checkTime(crontab_time string,StrNowTime string) bool {
	CronTimes := strings.Split(crontab_time, " ")
	NowTimes := strings.Split(StrNowTime, " ")

	for i := 0;i < len(NowTimes);i++{
		if !inTime(CronTimes[i],NowTimes[i]){
			return false
		}
	}
	return true
}

func inTime(TheCronTime string, TheNowTime string) bool {
	CronTimes := strings.Split(TheCronTime, ",")
	if len(CronTimes) < 1 {
		return false
	}
	if CronTimes[0] == "*" {
		return true
	}
	for _, CronTime := range CronTimes {
		if CronTime == TheNowTime {
			return true
		}
	}
	return false
}